<template>
  <el-dialog
    :title="$t('AbpIdentity[\'SelectUsers\']')"
    :visible.sync="visible"
    :before-close="closeDialog"
    :close-on-click-modal="false"
  >
    <el-form
      ref="memberQueryForm"
      label-position="top"
      :model="listContext"
      @submit.native.prevent
    >
      <el-form-item prop="filter">
        <el-input v-model="listContext.filter" :placeholder="$t('AbpIdentity[\'Search\']')" @keyup.enter.native="fetchData">
          <el-button slot="append" icon="el-icon-search" @click="fetchData"></el-button>
        </el-input>
      </el-form-item>

    </el-form>
    <el-table
      ref="memberTable"
      v-loading="listLoading"
      :data="list"
      row-key="id"
      :element-loading-text="$t('AbpIdentity[\'LoadingWithThreeDot\']')"
      border
      fit
      highlight-current-row
      @sort-change="sortChange"
    >
      <el-table-column
        type="selection"
        width="55"
        reserve-selection
        :selectable="row => !addedMembers[row.id]"
      />
      <el-table-column :label="$t('BookStore2[\'DisplayName:UserName\']')" prop="userName" sortable="custom">
        <template slot-scope="scope">
          {{ scope.row.userName }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('AbpIdentity[\'DisplayName:Name\']')" prop="name" sortable="custom">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('AbpIdentity[\'DisplayName:Email\']')" prop="email" sortable="custom">
        <template slot-scope="scope">
          {{ scope.row.email }}
        </template>
      </el-table-column>
    </el-table>
    <div class="block" style="margin-top: 10px">
      <el-pagination
        :page-sizes="pageContext.pageSizes"
        :page-size.sync="listContext.maxResultCount"
        :current-page.sync="pageContext.currentPage"
        :total="pageContext.totalCount"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="fetchData"
        @current-change="handleCurrentChange"
      />
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">{{ $t('AbpIdentity[\'Cancel\']') }}</el-button>
      <el-button type="primary" @click="submitForm">
        <i class="el-icon-check" />
        {{ $t('AbpIdentity[\'Save\']') }}
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getList } from '@/api/administration/user/user'
import { getMemberList, addMember } from '@/api/administration/organizationUnit/organizationUnit'
export default {
  name: 'AddMember',
  props: {
    context: {
      type: Object,
      required: true
    },
    visible: {
      type: Boolean,
      required: true,
      default: false
    }
  },
  data() {
    return {
      listLoading: false,
      list: [],
      pageContext: {
        pageSizes: [10, 25, 50, 100],
        totalCount: 0,
        currentPage: 1
      },
      listContext: {
        filter: '',
        sorting: '',
        skipCount: 0,
        maxResultCount: 10
      },
      addedMembers: {}
    }
  },
  watch: {
    async context(newVal, oldVal) {
      await this.fetchAddedMembers(newVal.ouId)
      this.fetchData()
    }
  },
  methods: {
    async fetchAddedMembers(ouId) {
      (await getMemberList(ouId)).items.forEach(member => {
        this.addedMembers[member.id] = member
      })
    },
    fetchData() {
      this.listLoading = true
      getList(this.listContext).then(resp => {
        this.list = resp.items
        this.pageContext.totalCount = resp.totalCount
        this.$nextTick(() => this.list.forEach(m => this.addedMembers[m.id] && this.$refs.memberTable.toggleRowSelection(m, true)))
      }).finally(() => {
        this.listLoading = false
      })
    },
    handleCurrentChange(currentPage) {
      this.listContext.skipCount = (currentPage - 1) * this.listContext.maxResultCount
      this.fetchData()
    },
    sortChange({ prop, order }) {
      this.listContext.sorting = ''
      if (order) {
        this.listContext.sorting = prop + ' ' + order
      }
      this.fetchData()
    },
    async submitForm() {
      const selectedRows = this.$refs.memberTable.selection
      const userIds = []
      selectedRows.forEach(select => {
        if (!this.addedMembers[select.id]) {
          userIds.push(select.id)
        }
      })
      await addMember(this.context.ouId, { userIds: userIds })
      this.$message({ message: this.$t('AbpIdentity[\'Ok\']'), type: 'success' })
    },
    closeDialog() {
      this.resetDialog()
      this.$emit('update:visible', false)
    },
    resetDialog() {
      this.listContext.filter = ''
      this.listContext.sorting = ''
      this.listContext.skipCount = 0
      this.listContext.maxResultCount = 10
      this.addedMembers = {}
      this.$refs.memberTable.clearSelection()
      this.$refs.memberTable.clearSort()
    }
  }
}
</script>
<style scoped>
</style>
